package iso8583

import (
	"encoding/json"
	"strconv"
)

const (
	FIX    = "fix"
	LLVAR  = "llvar"
	LLLVAR = "lllvar"
)
const (
	MSG    = -1
	BITMAP = -1000
)

const (
	FIELD_NOT_USE = -1000
)

const (
	BCD_LEFT  = "bcd_left"
	BCD_RIGHT = "bcd_right"
	HEX       = "hex"
	BIN       = "bin"
	ASCII     = "ascii"
)

type Result map[int][]byte

type lenSection struct {
	_type  string
	encode string
}

type dataSection struct {
	encode string
	maxLen int
}
type field struct {
	num int
	lenSection
	dataSection
}

type template [64]field

type jsonStruct struct {
	Field       string `json:"field"`
	Type        string `json:"type"`
	Len_encode  string `json:"len_encode"`
	Data_len    string `json:"data_len"`
	Data_encode string `json:"data_encode"`
}

type Iso struct {
	template
}

func New(js string) (*Iso, error) {
	var input [64]jsonStruct
	var iso Iso

	err := json.Unmarshal([]byte(js), &input)
	if err != nil {
		return nil, err
	}

	for i := 0; i < 64; i++ {
		iso.template[i].num, err = strconv.Atoi(input[i].Field)
		if err != nil {
			iso.template[i].num = FIELD_NOT_USE
		}
		iso.template[i].lenSection._type = input[i].Type
		iso.template[i].lenSection.encode = input[i].Len_encode
		iso.template[i].dataSection.encode = input[i].Data_encode
		iso.template[i].dataSection.maxLen, _ = strconv.Atoi(input[i].Data_len)
	}

	return &iso, nil
}

func (result Result) Get(num int) []byte {
	if v, ok := result[num]; ok {
		return v
	}
	return nil
}

//
